package com.dsj.util;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class Encrypt {
    private static final String SALT = "MyFixedSaltValue";

    public static void main(String[] args) {
        String password = "123456";
        String encryptedPassword = encryptPassword(password);
        System.out.println("Encrypted Password: " + encryptedPassword);
    }

    public static String encryptPassword(String password) {
        try {
            // 使用固定的盐值
            byte[] salt = SALT.getBytes(StandardCharsets.UTF_8);

            // 设置迭代次数和密钥长度
            int iterations = 3;
            int keyLength = 256;

            // 使用 PBKDF2 进行加密
            PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, keyLength);
            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
            byte[] encodedHash = factory.generateSecret(spec).getEncoded();

            // 将加密后的密码转换为十六进制字符串
            return bytesToHex(encodedHash);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 将字节数组转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
